package cn.est.controller;

import cn.est.dto.Result;
import cn.est.exceptions.FileException;
import cn.est.service.FileService;
import cn.est.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

@Api
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private FileService  fileService;


    //文件上传到oss服务器
    @ApiOperation(value ="文件上传" )
    @PostMapping("/upload")
    public Result upload(@RequestParam("file")MultipartFile multipartFile){
        if(multipartFile!=null){
            try {
                String path = fileService.upload(multipartFile);

                return ResultUtils.returnDataSuccess(path);
            } catch (FileException e) {
                e.printStackTrace();
            }
        }
        return ResultUtils.returnFail();
    }



    //删除oss服务器内容
    @ApiOperation(value = "删除oss服务器的文件")
    @GetMapping("/delete/{fileName}")
    public  Result deleteFile(@PathVariable("fileName") String fileName){

        if(fileName!=null&&!fileName.equals("")){
            try {
                //数据库中查询，比如说获取用户的头像，根据用户id获取头衔url,我们此处模拟一个path
                String path="2021/05/09/"+fileName;
                if(fileService.delete(path)){
                    return ResultUtils.returnSuccess();
                }
            } catch (FileException e) {
                e.printStackTrace();
            }
        }
        return ResultUtils.returnFail();
    }

    //从oss服务器中下载文件

    /**
     * 下载
     * @param fileName
     * @param response
     * @return
     */
    @ApiOperation(value = "文件的下载")
    @GetMapping("download/{fileName}")
    public Result download(@PathVariable("fileName")String fileName, HttpServletResponse response){

        try {
            fileService.download(fileName,response);
            return ResultUtils.returnSuccess();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResultUtils.returnFail();

    }


}
